package com.kevin.S2SM.filter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;

@WebFilter(filterName = "UserLogFilter", urlPatterns = "/*")
public class UserLogFilter implements Filter {

	private Logger logger;

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		String log_ip = request.getLocalAddr();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date now = new Date(System.currentTimeMillis());
		MDC.put("usr_id", "kevin");
		MDC.put("log_datetime", format.format(now));
		MDC.put("log_ip", log_ip);

		if (logger.isInfoEnabled()) {
			logger.info(MDC.getContext());
		}

		chain.doFilter(request, response);

	}

	public void init(FilterConfig arg0) throws ServletException {
		logger = Logger.getLogger(UserLogFilter.class);
	}

}
